package com.example.fruitshop;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class OrderActivity extends AppCompatActivity {
    private ArrayList<Product> selectedProducts;

    ActivityResultLauncher<Intent> activityResultLaunch;

    {
        activityResultLaunch = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            Intent intent = result.getData();
                            if (intent != null) {
                                selectedProducts = (ArrayList<Product>) intent.getExtras().getSerializable("selectedProducts");
                                showSelectedProducts();
                            }
                        }
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        TextView textAddress = findViewById(R.id.text_address);
        Button btnGoMarket = findViewById(R.id.btn_go_shop);

        Address address = (Address) getIntent().getSerializableExtra("address");
        textAddress.setText(String.format("你选择的收货地址为：\n%s", address));

        btnGoMarket.setOnClickListener(view -> activityResultLaunch.launch(new Intent(this, MarketActivity.class)));
    }

    private void showSelectedProducts() {
        ArrayList<String> products = new ArrayList<>();
        for (int i = 0; i < selectedProducts.size(); i++) {
            String productName = selectedProducts.get(i).getProductName();
            products.add(productName);
        }
        ListView listView = findViewById(R.id.list_selected_products);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, products);
        listView.setAdapter(arrayAdapter);

    }
}
